<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="true"
    class="open-invoice-common-dialog small-common-dialog-size"
    width="450px">
    <div class="main">
      <div :style="!summary ? 'margin-bottom: 20px': 'margin-bottom: 0'">
        <Title :title="title" font-size="16px" />
        <div v-if="summary" class="summary">
          <img src="../../../assets/hint.png" alt="">
          <div class="content">{{ summary }}</div>
        </div>
      </div>
      <el-form
        ref="orderForm"
        :rules="rules"
        :model="formData"
        label-position="left"
        label-width="80px"
        class="setting-form">
        <el-form-item v-if="showSendCheckbox" label-width="0px" label="" prop="userId" style="margin-bottom: 10px">
          <div :style="summary ?{textAlign:'center',marginTop: '14px'}:'margin-left: 80px'">
            <el-checkbox v-model="isSendMsg"><span style="color: #FD8546;">发送飞书通知</span></el-checkbox>
          </div>
        </el-form-item>
        <el-form-item v-if="isSendMsg" label="接收人" prop="userId" style="margin-bottom: 10px !important;">
          <template v-if="!receiveDisabled">
            <selectWithUserLoad
              v-if="selectWithUserLoad"
              ref="selectOrderOperator"
              :disabled="receiveDisabled"
              v-model="receiveUsers"
              :default-list="defaultObjectUser || []"
              :extend-params="{
                type: 1,
                authUrl
              }"
              key-name="id"
              style="width: 240px;"
              label-name="userName"
              multiple
              filterable
              collapse-tags
              clearable
            />
            <selectWithoutHttp
              v-if="!selectWithUserLoad"
              ref="selectOrderOperator"
              :disabled="receiveDisabled"
              v-model="receiveUsers"
              :default-list="defaultObjectUser || []"
              :list-data="defaultList"
              :value-type="'object'"
              style="width: 240px;"
              label-name="userName"
              multiple
              filterable
              collapse-tags
              clearable
            />
          </template>
          <div v-else-if="defaultObjectUser">
            <el-tag v-for="(item,index) in defaultObjectUser" :key="index" style="height: 25px;line-height: 24px;margin-right:5px;padding: 0 7px;">{{ item.userName }}</el-tag>
          </div>
        </el-form-item>
        <el-form-item v-if="isSendMsg || isShowInput" :label="summaryTitle" prop="dingTalkMsg" style="margin-bottom: 10px;">
          <el-input
            :rows="4"
            v-model="formData.dingTalkMsg"
            :placeholder="`${summaryTitle?`请输入${summaryTitle}`:'请输入内容'}`"
            resize="none"
            style="font-size: 13px;"
            type="textarea"
            maxlength="100"/>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="isReminder" class="tip">该审批将发送至对方飞书工作通知且进行加急</div>
    <div v-if="isReminder" class="warn-tip">非紧急审批，请勿随意加急，避免影响主管审批！</div>
    <div class="btn-container">
      <el-button :loading="loading" type="primary" size="small" @click="handelOK()">{{ btn1 }}</el-button>
      <el-button class="cancel-btn-style" type="info" size="small" @click="handleClose">{{ btn2 }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getDepartmentUser } from '@/api/auth';
import { allDeptlist } from '@/api/select';
import { handelDepartmentData, getDepartmentTreePath } from '@/utils';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import ElMessage from '@/utils/message';

import Title from '@/components/Title';
export default {
  components: {
    Title,
    selectWithUserLoad,
    selectWithoutHttp },
  props: {
    summaryTitle: {
      type: String,
      default: '任务描述'
    },
    title: {
      type: String,
      default: ''
    },
    btn1: {
      type: String,
      default: ''
    },
    btn2: {
      type: String,
      default: ''
    },
    summary: {
      type: String,
      default: ''
    },
    requestDept: {
      type: Boolean,
      default: false
    },
    isShowInput: {
      type: Boolean,
      default: false
    },
    status: {
      type: Number,
      default: 1
    },
    allDeptList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 用户列表权限配置
    // 例如搜索有审批客户结算单权限的用户
    // crm:customer:examine
    authUrl: {
      type: String,
      default: ''
    },
    // 是否展示发送飞书通知选择按钮
    showSendCheckbox: {
      type: Boolean,
      default: true
    },
    // 接收人是否要请求接口
    selectWithUserLoad: {
      type: Boolean,
      default: true
    },
    // 无需请求接口，下拉默认数组
    defaultList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    // 钉钉通知跳转地址
    redirectUrl: {
      type: String,
      default: '/client/customersettle'
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      callbackFun: null,
      isSendMsg: true,
      receiveUsers: [],
      formData: {
        dingTalkMsg: ''
      },
      extendParams: null,
      receiveDisabled: false,
      deptList: [],
      allCascaderProps: {
        multiple: true,
        value: 'id',
        label: 'value'
      },
      defaultObjectUser: [],
      cascaderProps: {
        multiple: true,
        lazy: true,
        value: 'id',
        label: 'value',
        lazyLoad(node, resolve) {
          const { level } = node;
          if (level < 2 && !node.root && node.data) {
            const params = { id: node.data.id };
            getDepartmentUser(params).then(res => {
              handelDepartmentData(res.data);
              resolve(res.data);
            });
          } else {
            resolve();
          }
        }
      }
    };
  },
  computed: {
    deptListOption: {
      get: function() {
        if (!this.requestDept) {
          return this.allDeptList;
        } else {
          return this.deptList;
        }
      }
    },
    isReminder() { // 是否是催办
      return this.title === '催办通知';
    },
    rules() {
      const res = {
        'dingTalkMsg': [{ required: true, message: `请填写${this.summaryTitle}`, trigger: 'blur' }]
      };
      return this.isReminder ? res : {};
    }
  },
  created() {
    if (this.requestDept) {
      // this.getAllDeptList();
    }
  },
  methods: {
    handleClose() {
      // 如果是结算单列表，关闭弹窗要清空已选人员
      if (this.$route.name === 'customersettle') {
        this.receiveUsers = [];
      }
      this.$refs.orderForm.clearValidate();
      this.dialogVisible = false;
    },
    showDialog({ defaultMsg, defaultUser, extendParams, defaultObjectUser, receiveDisabled }) {
      this.extendParams = extendParams || null;
      this.receiveDisabled = receiveDisabled || false;
      if (defaultUser) {
        this.receiveUsers = defaultUser;
      }
      if (defaultObjectUser) {
        const list = _.uniqBy(defaultObjectUser, 'id');
        this.defaultObjectUser = list;
        this.receiveUsers = list.map(i => i.id);
      }
      this.formData.dingTalkMsg = defaultMsg || '';
      this.dialogVisible = true;
    },
    setUserDefault(defaultUserId) {
      if (defaultUserId.length) {
        const userIds = [];
        for (let i = 0; i < this.deptListOption.length; i++) {
          const item = getDepartmentTreePath(this.deptListOption[i]);
          for (let d = 0; d < item.length; d++) {
            const itemD = item[d];
            const itemLength = itemD.length === 0 ? 0 : itemD.length;
            const lastItem = itemD[itemLength - 1];
            if (defaultUserId.indexOf(lastItem) >= 0) {
              userIds.push(itemD);
            }
          }
        }
        return userIds;
      } else {
        return [];
      }
    },
    handelOK() {
      if (this.isReminder) { // 仅催办校验表单
        let isValid = true;
        this.$refs.orderForm.validate((valid) => {
          isValid = valid;
        });
        if (!isValid) return;
      }
      if (this.isSendMsg && (this.receiveUsers.length === 0 || this.formData.dingTalkMsg === '')) {
        ElMessage.error(`请填写接收人和${this.summaryTitle}`);
        return;
      }
      let receiveUsers = '';
      if (this.receiveUsers && this.receiveUsers.length && this.receiveUsers[0].id) {
        receiveUsers = this.receiveUsers.map((item) => {
          return item.id;
        });
      }
      const data = {
        isSendMsg: this.isSendMsg,
        receiveUsers: (receiveUsers.length > 0 ? receiveUsers : this.receiveUsers).join(','),
        dingTalkMsg: this.formData.dingTalkMsg,
        url: `${location.origin}?redirect=${this.redirectUrl}`
      };
      if (this.extendParams)Object.assign(data, this.extendParams);
      if (this.status === 0) data.status = 0;
      this.$emit('handelOK', data);
      this.handleClose();
    },
    getAllDeptList() {
      allDeptlist().then(res => {
        handelDepartmentData(res.data);
        this.deptList = res.data;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.main {
  .summary {
    margin-top: 4px;
    img {
      display: block;
      margin: 0 auto;
      width: 80px;
      height: 80px;
    }
    .content {
      font-size: 20px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 20px;
      margin-top: 28px;
      text-align: center;
      line-height: 1.2;
    }
  }
  & ::v-deep {
    .el-input {
      width: 240px;
      .el-input__inner {
        height: 32px;
        width: 240px;
      }
      .el-input__suffix {
        display: flex;
        align-items: center;
      }
    }
    .el-textarea__inner {
      padding: 5px 5px 5px 10px;
      width: 240px;
    }
    .el-tag--info {
      color: #406EFF;
      background-color: #ecf1ff;
      display: flex;
      justify-content: center;
      align-items: baseline;
    }
  }
}
.tip, .warn-tip {
  font-size: 12px;
  text-align: center;
}
.tip {
  color: #999999;
  margin: 18px 0 0 46px;
}
.warn-tip {
  color: #FF4E5F;
  margin-left: 68px;
}
.btn-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
</style>
